from random import randint
import traceback
from django.db import connection
import json
import math
import sys
from MyDjango.globalData import *


def questions(request):
    print(request.META['REMOTE_ADDR'], 'questions', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_questions)
    if ans == format_error:
        return ans
    sys.stdout.flush()

    data = rand_ques_num(ans, 100)

    if data is None or len(data) == 0:
        return JsonResponse({'code': 0, 'message': '没有符合要求的题目', 'data': None})

    qs = gen_qs(data)

    # print(len(qs))
    d = {"gradeName": ans['gradeName'],
         "type": ans['type'],
         "questions": qs
         }
    return JsonResponse({'code': 0,
                         'message': "随机返回100道题",
                         'data': d})


def exam(request):
    print(request.META['REMOTE_ADDR'], 'exam', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_questions)
    if ans == format_error:
        return ans
    sys.stdout.flush()

    data = rand_ques_num(ans, 30)

    if data is None or len(data) == 0:
        return JsonResponse({'code': 0, 'message': '没有符合要求的题目', 'data': None})

    qs = gen_qs(data)

    # print(len(qs))
    d = {"gradeName": ans['gradeName'],
         "type": ans['type'],
         "questions": qs
         }
    return JsonResponse({'code': 0,
                         'message': "随机返回30道题",
                         'data': d})


def rand_ques_num(ans, num):
    cursor = connection.cursor()
    sql = 'select id,grade,typ,string,answer,A,B,C,D from bank '
    if ans['gradeName'] != '' or ans['type'] != '':
        sql += 'where '
        if ans['gradeName'] != '':
            sql += 'grade = "{}" '.format(grade[ans['gradeName'].strip()])
            if ans['type'] != '':
                sql += 'and typ = "{}" '.format(ans['type'])
        else:
            sql += 'typ = "{}" '.format(ans['type'])
    sql += 'order by rand() limit {}'.format(num)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    return data


def Json(r, s):
    try:
        if r in [b'', b'{}']:
            return format_error
        ans = json.loads(r)
        if not s == set(ans):
            print(ans)
            print(s, set(ans))
            sys.stdout.flush()
            return format_error
        return ans
    except:
        print(traceback.print_exc())
        sys.stdout.flush()
        return format_error


def search(request):
    print(request.META['REMOTE_ADDR'], 'search', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_search)
    if ans == format_error:
        return ans
    sys.stdout.flush()
    # print(ans)

    cursor = connection.cursor()
    sql = '''select id,grade,typ,string,answer,A,B,C,D from bank 
    where grade like "%{}%" and typ like "%{}%" and string like "%{}%"'''.format(
        grade[ans['gradeName'].strip()], ans['type'].strip(), ans['name'].strip())
    # print(sql)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    # print(data)
    if data is None or len(data) == 0:
        return JsonResponse({'code': 0, 'message': '没有符合要求的题目', 'data': None})

    d = {'code': 0,
         'message': '查询题目',
         'data': {'page': ans['page'],
                  'size': ans['size'],
                  'total': len(data)}}

    if ans['page'] > len(data) / ans['size']:
        ans['page'] = math.ceil(len(data) / ans['size'])
    if len(data) > ans['size']:
        data = data[(ans['page'] - 1) * ans['size']:]
        if len(data) > ans['size']:
            data = data[:ans['size']]

    d['data']['questions'] = gen_qs(data)

    return JsonResponse(d)


def gen_qs(data):
    qs = []
    # id,grade,typ,string,answer,A,B,C,D
    for line in data:
        answers = [{'choice': 'A. ' + line[5], 'check': False},
                   {'choice': 'B. ' + line[6], 'check': False},
                   {'choice': 'C. ' + line[7], 'check': False},
                   {'choice': 'D. ' + line[8], 'check': False}]
        print(line[4])
        answers[ord(line[4]) - ord('A')]['check'] = True
        qs.append({'stemId': line[0],
                   'gradeName': grade[line[1]],
                   'type': line[2],
                   'name': line[3],
                   'answers': answers})
    return qs


def id(request):
    print(request.META['REMOTE_ADDR'], 'id', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_id)
    if ans == format_error:
        return ans
    sys.stdout.flush()

    cursor = connection.cursor()
    sql = '''select id,grade,typ,string,answer,A,B,C,D from bank where id like "%{}%"'''.format(ans['stemId'].strip())
    # print(sql)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    if data is None or len(data) == 0:
        return JsonResponse({'code': 0, 'message': '查无此题', 'data': None})
    d = {"code": 0,
         "message": "根据题干id查询题目",
         "dataList": gen_qs(data)}
    return JsonResponse(d)


def insert(request):
    print(request.META['REMOTE_ADDR'], 'insert', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_insert)
    if ans == format_error:
        return ans
    if '' in ans.values():
        return format_error
    sys.stdout.flush()

    sql1 = 'insert into bank values("'
    sql2 = '","{}","{}","{}","{}","{}","{}","{}","{}")'.format(grade[ans['gradeName']], ans['type'],
                                                               ans['string'], ans['answer'],
                                                               ans['A'], ans['B'], ans['C'], ans['D'])
    stemId = '{}{}{:010}'.format(typ[ans['type']], grade[ans['gradeName']], randint(0, 9999999999))
    sql = sql1 + stemId + sql2
    # print(sql)
    cursor = connection.cursor()
    while True:
        try:
            sql = sql1 + stemId + sql2
            cursor.execute(sql)
        except:
            stemId = '{}{}{:010}'.format(typ[ans['type']], grade[ans['gradeName']], randint(0, 9999999999))
        else:
            break
    cursor.close()
    return JsonResponse({'code': 0, 'message': '新增成功', 'data': {"id": stemId}})


def update(request):
    print(request.META['REMOTE_ADDR'], 'update', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_update)
    if ans == format_error:
        return ans
    if '' in ans.values():
        return format_error
    sys.stdout.flush()

    sql = '''UPDATE bank SET grade="{}" , typ="{}" , 
    string="{}" , answer="{}" , A="{}" , B="{}" , C="{}" , D="{}"
        WHERE id='{}';'''. \
        format(grade[ans['gradeName']], ans['type'],
               ans['string'], ans['answer'],
               ans['A'], ans['B'], ans['C'], ans['D'], ans['id'])
    # print(sql)
    cursor = connection.cursor()
    try:
        cursor.execute(sql)
    except:
        return JsonResponse({'code': -1, 'message': '修改失败', 'data': None})
    finally:
        cursor.close()
    return JsonResponse({'code': 0, 'message': '修改成功', 'data': None})


def delete(request):
    print(request.META['REMOTE_ADDR'], 'delete', request.body, '\n')
    sys.stdout.flush()
    ans = Json(request.body, s_delete)
    if ans == format_error:
        return ans
    if ans['id'] == '':
        return format_error
    sys.stdout.flush()

    sql = '''delete from bank where id='{}';'''.format(ans['id'])
    # print(sql)
    cursor = connection.cursor()
    try:
        cursor.execute(sql)
    except:
        return JsonResponse({'code': -1, 'message': '删除失败', 'data': None})
    finally:
        cursor.close()
    return JsonResponse({'code': 0, 'message': '删除成功', 'data': None})
